package com.example.springbootdemo2;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RestController
@RequestMapping("param")
public class SessionController {
    @RequestMapping("/m10")
    public String getCookie1(HttpServletRequest request, HttpServletResponse response) {
        //获取所有 cookie 信息
        Cookie[] cookies = request.getCookies();
        StringBuilder builder = new StringBuilder();
        if(cookies != null) {
            for(Cookie cookie : cookies) {
                builder.append(cookie.getName() + ":" + cookie.getValue() + " ");
            }
        }
        return "Cookid信息:" + builder;
    }

    @RequestMapping("/getCookie")
    public String getCookie(@CookieValue("zhangsan") String value) {
        return "zhangsan:" + value;
    }

    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request) {
        //获取Session对象
        HttpSession session = request.getSession();
        if(session!=null) {
            session.setAttribute("username","java");
        }
        return "session 存储成功";
    }

    @RequestMapping("/getSess")
    public String sess(HttpServletRequest request) {
        //如果 session 不存在, 不会自动创建
        HttpSession session = request.getSession(false);
        String username = null;
        if(session != null && session.getAttribute("username")!=null) {
            username = (String) session.getAttribute("username");
        }
        return "username:" + username;
    }

    @RequestMapping("/getSess2")
    public String sess2(@SessionAttribute(value = "username", required = false) String username) {
        return "username:" + username;
    }

    @RequestMapping("/getSess3")
    public String sess3(HttpSession session) {
        String username = (String) session.getAttribute("username");
        return "username:" + username;
    }
}
